package com.androidgame.framework;

import java.util.ArrayList;
import java.util.List;

//Implements the behavior to reuse previously created instances 
//instead of creating new instances of a class frequently
public class Pool<T> 
{
	//can store any type of object in our Pool
	
	//return a new object that has the generic type 
	//of the Pool/PoolObjectFactory instance
	public interface PoolObjectFactory<T> 
	{
		public T createObject();
	}
	
	//an ArrayList to store pooled objects
	private final List<T> freeObjects;
	
	//a PoolObjectFactory that is used to generate 
	//new instances of the type this class holds
	private final PoolObjectFactory<T> factory;
	
	//stores the maximum number of objects the Pool can hold
	private final int maxSize;
	
	public Pool(PoolObjectFactory<T> factory, int maxSize) 
	{
		this.factory = factory;
		this.maxSize = maxSize;
		this.freeObjects = new ArrayList<T>(maxSize);
	}
	
	//returns a new instance of the pool type via PoolObjectFactory.newObject() or
	//returns a pooled instance if there’s one in the freeObjects ArrayList
	public T newObject() 
	{
		T object = null;
		
		if (freeObjects.size() == 0)
		{
			object = factory.createObject();
		}
		
		else
		{
			object = freeObjects.remove(freeObjects.size() - 1);
		}
		
		return object;
	}
	
	//insert the object into the list if there is space
	public void free(T object) 
	{
		if (freeObjects.size() < maxSize)
		{
			freeObjects.add(object);
		}
	}
}